package com.zjzywl.iotSendthings.controller;


import com.zjzywl.iotSendthings.entity.IdentityCard;
import com.zjzywl.iotSendthings.entity.Verify;
import com.zjzywl.iotSendthings.repository.IdentityCardRepository;
import com.zjzywl.iotSendthings.repository.VerifyRepository;
import com.zjzywl.iotSendthings.util.FaceIdentifyServerDTO;
import com.zjzywl.iotSendthings.util.ImageTransferUtil;
import com.zjzywl.iotSendthings.util.WebResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;


/**
 * @author wangjie
 * @date 2019-11-08 14:37
 */
@RestController
@RequestMapping(value = "/face")
public class FaceIdentifyController extends BaseController {

    @Autowired
    private IdentityCardRepository iDrepository;

    @Autowired
    private VerifyRepository verifyRepository;

    /**
     * @return com.zjzywl.iotSendthings.util.WebResult
     * @description 人脸对比(宏森人脸对比服务)
     * @params [request]
     * @author wangjie
     * @date 2019/11/8 14:41
     */
    @GetMapping(value = "/comparison")
    public WebResult comparison(@RequestParam("uuid") String uuid) throws InterruptedException {
        //查询证件表获取要比对的照片
        IdentityCard idCard = iDrepository.findByUuid(uuid);
        //查询人脸抓拍表
        Verify verify = verifyRepository.findByUuid(uuid);
        //对比开始时间
        Long startTime = System.currentTimeMillis();
        while (idCard == null || verify == null) {
            Thread.sleep(1000);
            //查询证件表获取要比对的照片
            idCard = iDrepository.findByUuid(uuid);
            //查询人脸抓拍表
            verify = verifyRepository.findByUuid(uuid);
            //现在的时间
            Long nowTime = System.currentTimeMillis();
            //如果耗时超过10秒，返回对比失败
            if ((nowTime - startTime) > 10000) {
                return WebResult.FAIL("对比超时,未获取到图片");
            }
        }
        FaceIdentifyServerDTO faceIdentityDTO = new FaceIdentifyServerDTO();
        String idPhotoBase64 = ImageTransferUtil.GetImageStr(idCard.getPicturePath());
        String facePhotoBase64 = ImageTransferUtil.GetImageStr(verify.getPicture());
        /** 人脸识别dto赋值*/
        {
            faceIdentityDTO.setLengthCatch(facePhotoBase64.length());
            faceIdentityDTO.setLengthIDCard(idPhotoBase64.length());
            faceIdentityDTO.setPicdataCatch(facePhotoBase64);
            faceIdentityDTO.setPicdataIDCard(idPhotoBase64);
            faceIdentityDTO.setSource("1");
        }

        ResponseEntity<String> comparisonValue = null;
        //若出错，最多三次调用人脸对比服务
        try {
            logger.info("第一次调用人脸服务");
            comparisonValue = appConfig.restTemplate().postForEntity(appConfig.getFaceIdentifyUrl(), faceIdentityDTO.toString(), String.class);
        } catch (RestClientException e) {
            try {
                Thread.sleep(2000);
                logger.info("第二次调用人脸服务");
                //再次调用
                comparisonValue = appConfig.restTemplate().postForEntity(appConfig.getFaceIdentifyUrl(), faceIdentityDTO.toString(), String.class);
            } catch (RestClientException ex) {
                try {
                    Thread.sleep(2000);
                    logger.info("第三次调用人脸服务");
                    //再次调用
                    comparisonValue = appConfig.restTemplate().postForEntity(appConfig.getFaceIdentifyUrl(), faceIdentityDTO.toString(), String.class);
                } catch (RestClientException ex1) {
                    //对比失败
                    verify.setResult(3);
                    verifyRepository.save(verify);
                    e.printStackTrace();
                    return WebResult.FAIL("人脸服务调用出错,对比失败");
                }
            }
        }

        logger.info("人脸比对返回：{" + comparisonValue.getBody() + "}");
        JSONObject jsonObject = JSONObject.fromObject(comparisonValue.getBody());
        String result = (String) jsonObject.get("result");
        if (result.equals("success")) {
            //同一人
            verify.setResult(1);
        } else {
            //不同人
            verify.setResult(2);
        }
        verifyRepository.save(verify);
        return WebResult.OK(jsonObject);
    }

//    /**
//     * @return com.zjzywl.iotSendthings.util.WebResult
//     * @description 基于中科院seetaface2人脸识别
//     * @params [uuid]
//     * @author wangjie
//     * @date 2019/11/12 11:53
//     */
//    @GetMapping(value = "/seetaface")
//    public WebResult seetaface(@RequestParam("uuid") String uuid) throws Exception {
//        //查询证件表获取要比对的照片
//        IdentityCard idCard = iDrepository.findByUuid(uuid);
//        //查询人脸抓拍表
//        Verify verify = verifyRepository.findByUuid(uuid);
//        //对比开始时间
//        Long startTime = System.currentTimeMillis();
//        while (idCard == null || verify == null) {
//            Thread.sleep(1000);
//            //查询证件表获取要比对的照片
//            idCard = iDrepository.findByUuid(uuid);
//            //查询人脸抓拍表
//            verify = verifyRepository.findByUuid(uuid);
//            //现在的时间
//            Long nowTime = System.currentTimeMillis();
//            //如果耗时超过10秒，返回对比失败
//            if ((nowTime - startTime) > 10000) {
//                return WebResult.FAIL("未获取到图片");
//            }
//        }
//        //对比相似度
//        float score = 0;
//        try {
//            score = FaceHelper.compare(new File(idCard.getPicturePath()), new File(verify.getPicture())) * 100;
//            logger.info("人脸比对返回：{" + score + "}");
//            //返回值
//            Map<String, Object> map = new HashMap<>();
//            if (score > 50) {
//                //同一人
//                verify.setResult(1);
//                map.put("result", "success");
//            } else {
//                //不同人
//                verify.setResult(2);
//                map.put("result", "flad");
//            }
//            map.put("score", score);
//            verifyRepository.save(verify);
//            return WebResult.OK(map);
//        } catch (RestClientException e) {
//            //对比失败
//            verify.setResult(3);
//            verifyRepository.save(verify);
//            e.printStackTrace();
//            return WebResult.FAIL("对比失败");
//        }
//    }
}
